﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using WikiCsharpCommon;
using WikiCsharpCommon.Settings;
using System.IO;
using Common;

namespace WikiCSharpBugUpdater
{
    public partial class BugUpdater : Form
    {
        private string settings_path_;
        private string local_path_;
        private string parameters_filename_ = "parameters.xml";
        private MyBugtracker m_mbt = null;
        private WikiCsharpBugtracker m_wcbt = new WikiCsharpBugtracker();

        public BugUpdater()
        {
            InitializeComponent();

            local_path_ = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            settings_path_ = local_path_ + System.IO.Path.DirectorySeparatorChar + parameters_filename_;
        }
        
        public String BugId
        {
            get { return dgvList.CurrentRow.Cells["cIssueID"].Value.ToString(); }
        }

        private void BugUpdater_Load(object sender, EventArgs e)
        {
            MySettingsManager settings = new MySettingsManager("");

            if (File.Exists(settings_path_))
            {
                settings.Deserialize(settings_path_, ref settings);
            }

            m_mbt = new MyBugtracker(settings);

            if (!m_mbt.ValidateSettings())
            {
                WikiCsharpOptions wcso = new WikiCsharpOptions("");

                if (wcso.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    m_mbt = new MyBugtracker(new MySettingsManager(wcso.Options));

                    m_mbt.Settings.Serialize(settings_path_);
                }
            }
        
            if (m_mbt.ValidateSettings())
            {
                issueAssigneeDataGridViewTextBoxColumn.Items.Add("");
                issueAssigneeDataGridViewTextBoxColumn.Items.AddRange(m_wcbt.GetUserFullNameList(m_mbt.Settings.Folder));

                issueReporterDataGridViewTextBoxColumn.Items.Add("");
                issueReporterDataGridViewTextBoxColumn.Items.AddRange(m_wcbt.GetUserFullNameList(m_mbt.Settings.Folder));

                issueStatusDataGridViewTextBoxColumn.Items.AddRange(m_wcbt.GetStatusList(m_mbt.Settings.Folder));

                cboStatus.Items.Add("");
                cboStatus.Items.AddRange(m_wcbt.GetStatusList(m_mbt.Settings.Folder));

                cboAssignee.Items.Add("");
                cboAssignee.Items.AddRange(m_wcbt.GetUserFullNameList(m_mbt.Settings.Folder));

                cboReporter.Items.Add("");
                cboReporter.Items.AddRange(m_wcbt.GetUserFullNameList(m_mbt.Settings.Folder));

                cboAssignee.SelectedItem = m_wcbt.GetUserFullName(m_mbt.Settings.Folder, Environment.UserName);
                cboReporter.SelectedItem = m_wcbt.GetUserFullName(m_mbt.Settings.Folder, Environment.UserName);

                int default_status_index = m_wcbt.GetWIPStatusIndex(m_mbt.Settings.Folder) + 1;
                if (cboStatus.Items.Count > default_status_index)
                    cboStatus.SelectedIndex = default_status_index;
            }
        }

        private void cboStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            FeedList();

            UpdateFilter();
        }

        private void FeedList()
        {
            dsData.dtIssueData.Clear();

            if (string.IsNullOrEmpty(cboStatus.Text))
            {
                for (int i = 1; i < cboStatus.Items.Count; ++i)
                {
                    dsData.dtIssueData.Merge(m_wcbt.GetBugList(m_mbt.Settings.Folder, cboStatus.Items[i].ToString()));
                }
            }
            else
            {
                dsData.dtIssueData.Merge(m_wcbt.GetBugList(m_mbt.Settings.Folder, cboStatus.Text));
            }
        }

        private void filter_Changed(object sender, EventArgs e)
        {
            UpdateFilter();
        }

        private void UpdateFilter()
        {
            string filter = "IssueID LIKE '*" + txtIDFilter.Text + "*'";

            foreach(var summary in txtSummary.Text.Split(new string[]{" "}, StringSplitOptions.RemoveEmptyEntries))
                filter += " AND IssueSummary LIKE '*" + summary + "*'";

            if (!string.IsNullOrEmpty(cboAssignee.Text) && !string.IsNullOrEmpty(cboReporter.Text))
            {
                if (chkOR.Checked)
                {
                    filter += " AND (IssueAssignee = '" + cboAssignee.Text + "' OR IssueReporter = '" + cboReporter.Text + "')";
                }
                else
                {
                    filter += " AND IssueAssignee = '" + cboAssignee.Text + "' AND IssueReporter = '" + cboReporter.Text + "'";
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(cboAssignee.Text))
                {
                    filter += " AND IssueAssignee = '" + cboAssignee.Text + "'";
                }
                else if (!string.IsNullOrEmpty(cboReporter.Text))
                {
                    filter += " AND IssueReporter = '" + cboReporter.Text + "'";
                }
            }

            tIssuesBindingSource.RowFilter = filter;
        }

        private void dgvList_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            DataGridView grid = sender as DataGridView;
            DataGridViewCell cell = grid.CurrentCell;

            if (grid.IsCurrentCellDirty && !cell.EditedFormattedValue.Equals(cell.FormattedValue))
            {
                switch (cell.OwningColumn.DataPropertyName)
                {
                    case "IssueAssignee":
                        {
                            string assignee = m_wcbt.GetUserUsername(m_mbt.Settings.Folder, cell.EditedFormattedValue.ToString());
                            m_wcbt.ChangeBugAssignee(m_mbt.Settings.Folder, BugId, assignee);
                            break;
                        }
                    case "IssueReporter":
                        {
                            string reporter = m_wcbt.GetUserUsername(m_mbt.Settings.Folder, cell.EditedFormattedValue.ToString());
                            m_wcbt.ChangeBugReporter(m_mbt.Settings.Folder, BugId, reporter);
                            break;
                        }
                    case "IssueStatus":
                        {
                            string status = cell.EditedFormattedValue.ToString();
                            m_wcbt.ChangeBugState(m_mbt.Settings.Folder, BugId, status);
                            break;
                        }
                }
            }
            
            if (grid.IsCurrentCellDirty)
            {
                grid.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }

        private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            WikiCsharpOptions wcso = new WikiCsharpOptions(m_mbt.Settings.ToString());

            if (wcso.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                MySettingsManager settings = new MySettingsManager(wcso.Options);
                MyBugtracker mbt = new MyBugtracker(settings);

                if (mbt.ValidateSettings())
                {
                    m_mbt.Settings.Serialize(settings_path_);

                    m_mbt = new MyBugtracker(settings);
                }
            }
        }
    }
}
